let getPreInfo = require( '../weChat/getOpenId/index' );
let path = require( 'path' );
let fs = require( 'fs' );
let mustache = require( 'mustache' );
let request = require('request');
let { userInfoM } = require('../db');



const getUserData = ( openid, access_token ) => {

  return new Promise( ( resolve, reject ) => {
    // 有了token 再去获取用户的数


    request( {
      url: 'https://api.weixin.qq.com/sns/userinfo?' +
      'access_token=' + access_token +
      '&openid=' + openid +
      '&lang=zh_CN',
    }, (error, response, body) => {
      if (error){
        reject( response && response.statusCode + ': ' + error);
      } else {
        let result = JSON.parse( body );
        let { errcode, errmsg } = result;
        if ( errcode ){
          reject( '获取用户数据发生了错误 ' + errmsg );
        } else {
          resolve( result )
        }

      }

    })
  } );


};

//  将openid 对应的用户数据存入到数据库中
const saveToDb = userInfo => {
  let { openid = ''} = userInfo;

  // 更新数据库
  return userInfoM.get()
    .updateOne(
      { openid },
      { $set: userInfo },
      { upsert: true })
};

const returnHTML = ( res, openid ) => {
  console.log( openid, '进行了一次授权 <-- openid' );
  let page = fs.readFileSync( path.join( __dirname, '../static/template.html' ), "utf8" );
  let html = mustache.to_html( page, { openid } );
  res.send( html );
};

const mobileHome = ( req, res ) => {
  // 返回一个交互页面
  console.log( req.query, '/pay/被访问了' );
  let { code } = req.query;
  if ( !code ) throw Error( '初次授权绝对需要code' );

  // 获取 openid
  // openid 用来确认用户的身份
  getPreInfo( code )
    .then( ({ openid, access_token }) => {

      // 返回带有 openid 的模版
      returnHTML( res, openid );


      // 请求 openid 对应的用户的数据( 头像等 )
      getUserData( openid, access_token )
        .then( saveToDb )
        .catch( err => console.error( err ) );

      // 将用户数据存入数据库


    } );

};

module.exports = mobileHome;